package com.goldman.aplt.base.interceptor;
import com.fasterxml.jackson.core.type.TypeReference;
import com.goldman.aplt.base.constant.HeaderConst;
import com.goldman.aplt.util.CommUtil;
import com.goldman.http.common.s2s.util.JsonUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.goldman.aplt.base.constant.ApConstants.AP_RULE_PREFIX;

@Configuration
public class FeignInterceptor implements RequestInterceptor {

    @Resource
    private StringRedisTemplate strRedisTmpl;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header(HeaderConst.BUSI_SEQ, CommUtil.getTrxnEnvs().getBusi_seq());
        Object rule = CommUtil.getTrxnEnvs().getRule_buffer();
        //远程服务调用需要将当前的规则预埋数据带过去
        if(rule != null) {
            String key = AP_RULE_PREFIX+UUID.randomUUID();
            if(rule instanceof List) {
                Map<String, Object> r = JsonUtil.toList(JsonUtil.toJsonStr(rule), new TypeReference<List<Map<String, Object>>>(){}).get(0);
                strRedisTmpl.opsForValue().set(key, JsonUtil.toJsonStr(r).replaceAll("\\\\\"", "\""), 10, TimeUnit.MINUTES);
            } else {
                strRedisTmpl.opsForValue().set(key, JsonUtil.toJsonStr(rule).replaceAll("\\\\\"", "\""), 10, TimeUnit.MINUTES);
            }
            requestTemplate.header(HeaderConst.RULE_BUFFER, key);
        }
    }
}
